<template>
  <div class="ai-tools-detail-container">
    <ai-tools-top>
      <div slot="top-left"
        class="flex items-center md:flex-row md:gap-3 flex-wrap">
        <!-- <common-link path="/top-ai-tools"
          class="w-full md:w-auto text-base text-white font-bold hover:text-purple-1200">
          {{$t('aitools_inAITools')}}
        </common-link> -->
        <common-link path="/"
          class="text-base text-white hover:text-purple-1200 go-home">
          {{$t('home')}}
        </common-link>
        <div class="w-2.5 h-2.5 inline-block">
          <svg-icon className="text-white text-mini"
            iconName='right_outlined'></svg-icon>
        </div>
        <common-link path="/top-ai-tools"
          class="text-base text-white hover:text-purple-1200 go-prev">
          {{$t('aitools_topAITools')}}
        </common-link>
        <div class="w-2.5 h-2.5 inline-block">
          <svg-icon className="text-white text-mini"
            iconName='right_outlined'></svg-icon>
        </div>
        <span class="text-white text-base">
          {{top_article.title}}
        </span>

        <div class="w-full h-px my-2.5 md:w-px md:h-5 bg-white bg-opacity-30 md:mx-1.5 md:my-0"></div>
        <div class="w-full md:w-auto text-base text-white font-bold">
          {{$t('aitools_lastUpdated', {date: $formattedDate(top_article.published_at, fI18n, locale)})}}
        </div>
      </div>
    </ai-tools-top>

    <div class="pt-8 pb-12 px-4">
      <div class="max-w-15xl mx-auto">
        <h1 class="text-5xl leading-tight font-bold text-gray-2700 break-words mb-6">
          {{top_article.title}}
        </h1>
      </div>
      <div class="max-w-15xl mx-auto">
        <div class="grid gap-20 tools-box"
          :class="{'no-right': !(recommendToolsList && recommendToolsList.length > 0)}">
          <div class="box-left">
            <div class="mb-16 editor-bar"
              v-if="hasRealVal(top_article.content)"
              v-html="top_article.content">
            </div>
            <template v-if="hasRealVal(top_article.modules) && Array.isArray(top_article.modules) && top_article.modules.length > 0">
              <h2 class="text-3xl text-gray-2700 font-bold mb-9">
                {{$t('aitools_bestIn', {keyword: top_article.keyword, year: fullYear})}}
              </h2>
              <div class="space-y-12">
                <div class="tool-bar"
                  v-for="(item, key) in top_article.modules"
                  :id="item.handle">
                  <div class="flex items-center gap-8 mb-7 tool-dom"
                    :data-handle="item.handle"
                    :data-advertisement_id="item.advertisement_id ? item.advertisement_id : ''"
                    data-position="try"
                    :data-index="key">
                    <span class="flex h-16 w-16 p-2 bg-gray-2900 items-center justify-center text-3xl text-white font-bold">
                      {{key + 1}}
                    </span>
                    <h3>
                      <common-link path="/tool/:handle"
                        @click.native="handleExp(key, item, 'bestInTool')"
                        target="_blank"
                        :params="{ handle: item.handle}"
                        class="text-4xl text-gray-2700 font-bold hover:text-purple-1300">{{$websiteName(item)}}
                      </common-link>
                    </h3>
                    <a :href="item.website"
                      rel="nofollow"
                      class="group"
                      v-if="hasRealVal(item.website)"
                      @click="handleExp(key, item, 'bestInWebsite',item.website)"
                      target="_blank">
                      <svg-icon className="text-2xl text-gray-1500 group-hover:text-purple-1300 mt-0.5"
                        iconName='openTool'></svg-icon>
                    </a>
                  </div>
                  <div class="editor-bar"
                    v-html="item.content">

                  </div>
                  <div class="mt-12">
                    <common-link path="/tool/:handle"
                      @click.native="handleExp(key, item, 'bestInTry')"
                      target="_blank"
                      :params="{ handle: item.handle}"
                      class="inline-flex w-full bg-purple-2300 sm:w-auto text-center py-4 px-7 text-base text-white hover:bg-purple-1300">
                      <span class="text-lg text-white whitespace-nowrap">{{$t('aitools_try',{toolName: item.name})}}</span>
                    </common-link>
                  </div>
                </div>
              </div>
            </template>

            <div class="mt-16"
              v-if="hasRealVal(top_article.ends_content)">
              <h2 class="text-3xl text-gray-2700 font-bold mb-9">
                {{$t('aitools_finalWords')}}
              </h2>
              <div class="mt-7">
                <p class="text-xl text-gray-2700 leading-loose"
                  v-html="top_article.ends_content">
                </p>
              </div>
            </div>

            <h2 class="text-3xl text-gray-1000 font-bold mb-9 mt-16">
              {{$t('aitools_aboutTheAuthor')}}
            </h2>
            <div class="bg-purple-1600 p-5 mt-7 rounded-lg">
              <div class="flex items-center gap-3 mb-6">
                <div class="w-7 h-7 rounded-full overflow-hidden">
                  <img :src="require(`@/assets/images/avatar/${parseInt(top_article.author)+1}.png`)"
                    alt=""
                    srcset=""
                    class="w-full h-full">
                </div>
                <span class="text-base text-black"
                  v-html="$t('aitools_byAuthor',{author: authorOptions[parseInt(top_article.author)].author})"></span>
              </div>
              <p class="text-base text-gray-1000 mt-6">
                {{authorOptions[parseInt(top_article.author)].desc}}
              </p>
            </div>

            <div class="mt-16"
              v-if="hasRealVal(more_ai_tools) && more_ai_tools.length > 0">
              <h2 class="text-3xl text-gray-2700 font-bold mb-9">
                {{$t('aitools_moreAITools')}}
              </h2>
              <div class="mt-6">
                <ul class=" list-disc space-y-4 pl-5">
                  <li v-for="(item, key) in more_ai_tools"
                    :key="key"
                    class="flex items-start gap-3">
                    <i class="block flex-shrink-0 w-1.5 h-1.5 rounded-full bg-black mt-3.5"></i>
                    <common-link path="/top-ai-tools/:handle"
                      @click.native="handleExp(key, item, 'more_ai_tools')"
                      :data-handle="item.handle"
                      :data-advertisement_id="item.advertisement_id ? item.advertisement_id : ''"
                      data-position="more_ai_tools"
                      :data-index="key"
                      target="_blank"
                      :params="{ handle: item.handle}"
                      class="text-2xl text-purple-2300 hover:text-purple-1300 flex-1 w-0 break-word tool-dom">
                      {{item.title}}
                    </common-link>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div class="box-right">
            <div class="box-menu">
              <div class="box-nav">
                <div class="text-lg text-gray-2700 font-bold"
                  v-if="top_article.modules && top_article.modules.length > 0">
                  {{top_article.keyword}}
                </div>
                <div class="mt-3"
                  v-if="top_article.modules && top_article.modules.length > 0">
                  <ul class="space-y-1.5 pl-2">
                    <li v-for="(item, key) in top_article.modules"
                      :key="key"
                      class="flex items-start gap-3">
                      <a :href="`#${item.handle}`"
                        @click="toTooBar(item.handle)"
                        class="text-base text-gray-2700 hover:text-purple-1300 flex-1 w-0 break-word">
                        {{key+1}}. {{item.name}}
                      </a>
                    </li>
                  </ul>
                </div>
                <sponsored-by class="mt-4 text-lg text-gray-1000 font-semibold"></sponsored-by>
              </div>
            </div>
            <div class="box-featured"
              v-if="recommendToolsList && recommendToolsList.length > 0">
              <h2 class="text-lg text-gray-34 font-bold">{{$t('category_featured')}}</h2>
              <div class="tools space-y-4 mt-5"
                v-if="recommendToolsList && recommendToolsList.length > 0">
                <template v-for="(item, key) in recommendToolsList">
                  <min-tool-featured :key="item.handle+'-'+key"
                    v-if="key< 20"
                    :toolPosIndex="key"
                    :toolsData="item"></min-tool-featured>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <the-best-ai-websites></the-best-ai-websites>
  </div>
</template>

<script>
import authorOptions from '@/assets/json/authorOptions.json'
import moment from 'moment'
import mixinsExposure from '~/mixins/mixins-exposure'
import _ from 'lodash'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'AiToolsDetail',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
      script: [
        {
          json: {
            '@context': 'https://schema.org',
            '@type': 'Article',
            name: this.top_article.title,
            headline: this.top_article.contentn,
            image: this.getPic(),
            dateModified: this.top_article.updated_at
              ? moment(this.top_article.updated_at * 1000).format(
                  'YYYY-MM-DDTHH:mm:ssZ'
                )
              : null,
            datePublished: this.top_article.published_at
              ? moment(this.top_article.published_at * 1000).format(
                  'YYYY-MM-DDTHH:mm:ssZ'
                )
              : null,
            author: {
              '@type': 'Organization',
              name: this.authorOptions[parseInt(this.top_article.author)],
              url: 'https://www.toolify.ai',
            },
            description: this.description,
            articleSection: 'Technology',
            mainEntityOfPage: `https://www.toolify.ai${this.$route.fullPath}`,
            publisher: {
              '@context': 'https://www.toolify.ai',
              '@type': 'Organization',
              name: 'Toolify',
              legalName: 'Toolify Inc',
              url: 'https://www.toolify.ai',
              logo: 'https://www.toolify.ai/favicon.ico',
              foundingDate: '2023',
              founders: [
                {
                  '@type': 'Organization',
                  name: 'toolify',
                },
              ],
              address: {
                '@type': 'PostalAddress',
                streetAddress: '1942 Broadway St STE 314C Boulder',
                addressLocality: 'Colorado',
                addressRegion: 'CO',
                postalCode: '80302',
                addressCountry: 'US',
              },
              contactPoint: {
                '@type': 'ContactPoint',
                contactType: 'customer support',
                email: 'business@toolify.ai',
              },
              sameAs: ['https://twitter.com/samChan3890089'],
            },
            name: this.title,
            breadcrumb: {
              '@type': 'BreadCrumbList',
              itemListElement: [
                {
                  '@type': 'ListItem',
                  position: 1,
                  name: this.$t('home'),
                  item: `https://www.toolify.ai${
                    this.locale === 'en' ? '' : `/${this.locale}`
                  }`,
                },
                {
                  '@type': 'ListItem',
                  position: 2,
                  name: this.$t('aitools_topAITools'),
                  item: `https://www.toolify.ai${
                    this.locale === 'en' ? '' : `/${this.locale}`
                  }/top-ai-tools`,
                },
                {
                  '@type': 'ListItem',
                  position: 3,
                  name: this.$t('aitools_topAITools'),
                },
              ],
            },
          },
          type: 'application/ld+json',
        },
      ],
    }
  },
  async asyncData({ app, route, params, $axiosApi, error, store }) {
    try {
      let [articleRes, recommendRes] = await Promise.all([
        $axiosApi.getTopArticlesDetail(params.handle),
        $axiosApi.searchGetAd(),
        /* $axiosApi.getTools({
          page: 1,
          per_page: 100,
          history_has_recommended: 1,
        }), */
      ])
      let date = new Date()
      let fullYear = date.getFullYear()

      let description = null
      let title = null

      let top_article
      let more_ai_tools

      if (articleRes.code === 200) {
        description = articleRes.data.top_article.page_description
        title = articleRes.data.top_article.page_title
        top_article = articleRes.data.top_article
        more_ai_tools = articleRes.data.more_ai_tools
      } else {
        if (articleRes && articleRes.code && articleRes.code === 404) {
          error({ statusCode: 404 })
        } else if (
          !(articleRes && articleRes.code && articleRes.code === 401)
        ) {
          error({
            message: app.i18n.t('error_401'),
            statusCode: articleRes.code,
          })
        }
      }

      let recommendToolsList = []
      if (
        recommendRes.code === 200 &&
        recommendRes.data &&
        recommendRes.data.featured_list &&
        recommendRes.data.featured_list.length > 0
      ) {
        store.commit(
          'SET_TOP_ADVERTISER',
          JSON.parse(JSON.stringify(recommendRes.data.featured_list[0]))
        )
        recommendToolsList =
          recommendRes.data.featured_list &&
          recommendRes.data.featured_list.length > 0
            ? recommendRes.data.featured_list
            : []
      } else {
        store.commit('SET_TOP_ADVERTISER', null)
      }

      /* if (recommendRes.code === 200) {
        recommendToolsList =
          recommendRes.data.data && recommendRes.data.data.length > 0
            ? recommendRes.data.data
            : []
      } */

      return {
        top_article,
        more_ai_tools,
        title,
        description,
        recommendToolsList,
        fullYear,
      }
    } catch (err) {
      console.log(err)
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  mixins: [mixinsExposure],
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,

      top_article: null,
      more_ai_tools: [],
      recommendToolsList: [],
      fullYear: null,
      authorOptions: authorOptions,
    }
  },
  methods: {
    ...mapActions(['exposure']),
    handleExp(key = 0, toolsData, position = 'bestIn', target_url) {
      this.getThrottledClickFunction(toolsData, key, position, {
        target_url: target_url,
      })()
    },
    getThrottledClickFunction(toolsData, key, position, prePropertyObj) {
      let functionKey = `${toolsData.handle}-${key}-${position}`
      if (!this.throttledClickFunctions[functionKey]) {
        this.throttledClickFunctions[functionKey] = _.throttle(() => {
          let exporeData = this.getExporeData(
            toolsData,
            position,
            key,
            false,
            prePropertyObj
          )
          this.exposure({
            ...exporeData,
          })
        }, 2000) // 设置节流时间间隔
      }
      return this.throttledClickFunctions[functionKey]
    },
    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
    toTooBar(handle) {
      const dom = document.querySelector(`#${handle}`)
      if (dom) {
        const top =
          dom.offsetTop + document.querySelector('.tools-box').offsetTop

        const targetScrollPosition = Math.max(top - 100, 0)

        let timer = setTimeout(() => {
          this.$nextTick(() => {
            window.scrollTo({
              top: targetScrollPosition,
              behavior: 'auto',
            })

            this.$nextTick(() => {
              clearTimeout(timer)
            })
          })
        })
      }
    },
    getPic() {
      let imgArr = ['https://cdn.toolify.ai/default.webp']
      if (
        this.top_article &&
        this.top_article.modules &&
        this.top_article.modules.length > 0 &&
        this.hasRealVal(this.top_article.modules[0].image)
      ) {
        imgArr[0] = this.top_article.modules[0].image
      }
      return imgArr
    },
  },
}
</script>
<style lang='scss' scoped>
.ai-tools-detail-container {
  font-family: toolify-primary;
}
</style>
<style lang='scss'>
.editor-bar {
  * {
    max-width: 100%;
    word-wrap: break-word !important;
    word-break: normal !important;
  }
  li {
    display: list-item;
  }
  head {
    display: none;
  }
  table {
    display: table;
  }
  tr {
    display: table-row;
  }
  thead {
    display: table-header-group;
  }
  tbody {
    display: table-row-group;
  }
  tfoot {
    display: table-footer-group;
  }
  col {
    display: table-column;
  }
  colgroup {
    display: table-column-group;
  }
  td,
  th {
    display: table-cell;
  }
  caption {
    display: table-caption;
  }
  th {
    font-weight: bolder;
    text-align: center;
  }
  caption {
    text-align: center;
  }
  body {
    margin: 8px;
    line-height: 1.12;
  }
  h1 {
    font-size: 2em;
    margin: 0.67em 0;
  }
  h2 {
    font-size: 1.5em;
    margin: 0.75em 0;
  }
  h3 {
    font-size: 1.17em;
    margin: 0.83em 0;
  }
  h4,
  p,
  blockquote,
  ul,
  fieldset,
  form,
  ol,
  dl,
  dir,
  menu {
    margin: 1.12em 0;
  }
  h5 {
    font-size: 0.83em;
    margin: 1.5em 0;
  }
  h6 {
    font-size: 0.75em;
    margin: 1.67em 0;
  }
  h1,
  h2,
  h3,
  h4,
  h5,
  h6,
  b,
  strong {
    font-weight: bolder;
  }
  blockquote {
    margin-left: 40px;
    margin-right: 40px;
  }
  i,
  cite,
  em,
  var,
  address {
    font-style: italic;
  }
  pre,
  tt,
  code,
  kbd,
  samp {
    font-family: monospace;
  }
  pre {
    white-space: pre;
  }
  button,
  textarea,
  input,
  object,
  select {
    display: inline-block;
  }
  big {
    font-size: 1.17em;
  }
  small,
  sub,
  sup {
    font-size: 0.83em;
  }
  sub {
    vertical-align: sub;
  }
  sup {
    vertical-align: super;
  }
  table {
    border-spacing: 2px;
  }
  thead,
  tbody,
  tfoot {
    vertical-align: middle;
  }
  td,
  th {
    vertical-align: inherit;
  }
  s,
  strike,
  del {
    text-decoration: line-through;
  }
  hr {
    border: 1px inset;
  }
  ol,
  ul,
  dir,
  menu,
  dd {
    margin-left: 40px;
  }
  ol {
    list-style-type: decimal;
  }
  ol ul,
  ulol,
  ul ul,
  ol ol {
    margin-top: 0;
    margin-bottom: 0;
  }
  ul {
    list-style: disc;
  }
  ol {
    list-style: decimal;
  }
  u,
  ins {
    text-decoration: underline;
  }
  br:before {
    content: '';
  }
  p {
    margin: 0 0 30px;
  }
  img {
    display: block;
    margin: 0 auto 15px;
    max-width: 100%;
    height: auto;
  }
  ul {
    li {
      p {
        &:last-child {
          margin: 0 0 14px;
        }
      }
    }
  }
}
.tools-box {
  .box-right {
    display: none;
  }
}

@media (min-width: 1280px) {
  .tools-box {
    grid-template-columns: minmax(300px, 1fr) 300px;
    grid-column-gap: 5rem;
    position: relative;
    &.no-right {
      grid-template-columns: minmax(300px, 1fr) 0;
    }
    .box-left {
      order: 1;
    }
    .box-right {
      display: block;
      order: 1;
      height: 100%;
      .box-menu {
        margin-bottom: 64px;
      }
      .box-featured {
        display: block;
      }
    }
  }
}
@media (min-width: 1900px) {
  .tools-box {
    .box-left {
    }
    .box-right {
      .box-menu {
        position: absolute;
        top: 0;
        left: -17.5rem;
        bottom: 0;
        margin-bottom: 0;
        padding: 0;
        border: none;
        background: 0 0;
        margin-bottom: 0;
        .box-nav {
          overflow: hidden;
          position: sticky;
          top: 6.25rem;
          width: 15rem;
          max-height: 37.5rem;
          padding-right: 0.9375rem;
          transition: 0.25s ease-in-out;
          &::-webkit-scrollbar {
            display: none;
            width: 6px;
            height: 6px;
            background: transparent;
          }
          &::-webkit-scrollbar-thumb {
            background: transparent;
            border-radius: 4px;
          }
          &::-webkit-scrollbar-thumb {
            background: #c3c7d2;
          }
          &:hover::-webkit-scrollbar-thumb {
            background: #c3c7d2;
          }
          &::-webkit-scrollbar-track {
            display: none;
          }
          &:hover {
            overflow-y: auto;
            &::-webkit-scrollbar {
              display: block;
            }
          }
        }
      }
    }
  }
}
</style>
